<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

use Cache;
use App\Models\FarmProduct;
use App\Models\FarmCombination;

class FarmProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $category_id = $request->input('category_id');
        $key = __FUNCTION__ . $category_id;
        $result = Cache::remember($key, 7*24*60, 
            function() use ( $category_id ) {
                return FarmProduct::where('category_id', '=', $category_id)
                    ->orderBy('sort_order', 'ASC')
                    ->orderBy('id', 'ASC')
                    ->get();
            }
        );
        return response()->json($result);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $product = FarmProduct::where('id', '=', $id)
                ->first();
        $up = FarmCombination::where('parent_id', '=', $id)
                ->join('farm_products', 'farm_products.id', '=', 'farm_combinations.son_id')
                ->select('farm_combinations.*', 'farm_products.name')
                ->get();
        $down = FarmCombination::where('son_id', '=', $id)
                ->join('farm_products', 'farm_products.id', '=', 'farm_combinations.parent_id')
                ->select('farm_combinations.*', 'farm_products.name')
                ->get();
        return response()->json(
                ['product'=>$product, 'up'=>$up, 'down'=>$down]
            );
    }
}
